import { PiniaPluginContext } from 'pinia'
import { toRaw } from 'vue'
const __piniaKey = '__PINIAKEY__'
const getStorage = (key: string) => {
    return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : ''
}
const setStorage = (key: string, value: any) => {
    localStorage.setItem(key, JSON.stringify(value))
}
const piniaPlugin = (options: { key?: string }) => {
    return (context: PiniaPluginContext) => {
        const { store } = context
        let data
        if (store.$id === 'User') {
            data = getStorage(`${options.key}??${__piniaKey}-${store.$id}`)
            store.$subscribe(() => {
                console.log('--subscribe', store.$state)
                setStorage(`${options.key}??${__piniaKey}-${store.$id}`, toRaw(store.$state))
            })
        }

        return { ...data }
    }
}

export default piniaPlugin